package com.github.boluo1230.wechat.service.sys.impl;

import com.github.boluo1230.wechat.constant.SysConstant;
import com.github.boluo1230.wechat.dao.SysMenuDao;
import com.github.boluo1230.wechat.entity.sys.SysMenuEntity;
import com.github.boluo1230.wechat.service.sys.SysMenuService;
import com.github.boluo1230.wechat.service.sys.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysUserService sysUserService;

    @Override
    public List<SysMenuEntity> queryListParentId(Integer parentId, List<Integer> menuIdList) {
        List<SysMenuEntity> menuList = queryListParentId(parentId);
        if (menuIdList == null) {
            return menuList;
        }
        return menuList.stream()
                .filter(x -> menuIdList.contains(x.getMenuId()))
                .collect(Collectors.toList());
    }

    @Override
    public List<SysMenuEntity> queryListParentId(Integer parentId) {
        return sysMenuDao.queryListParentId(parentId);
    }

    @Override
    public List<SysMenuEntity> queryNotButtonList() {
        return sysMenuDao.queryNotButtonList();
    }

    @Override
    public List<SysMenuEntity> getUserMenuList(Integer userId) {
        //系统管理员，拥有最高权限
        if (userId == SysConstant.UserType.SUPER_ADMIN.getType()) {
            return getAllMenuList(null);
        }

        //用户菜单列表
        List<Integer> menuIdList = sysUserService.queryAllMenuId(userId);
        return getAllMenuList(menuIdList);
    }

    /**
     * 获取所有菜单列表
     */
    private List<SysMenuEntity> getAllMenuList(List<Integer> menuIdList) {
        //查询根菜单列表
        List<SysMenuEntity> menuList = queryListParentId(0, menuIdList);
        //递归获取子菜单
        getMenuTreeList(menuList, menuIdList);

        return menuList;
    }

    /**
     * 递归
     */
    private List<SysMenuEntity> getMenuTreeList(List<SysMenuEntity> menuList, List<Integer> menuIdList) {
        List<SysMenuEntity> subMenuList = new ArrayList<>();
        for (SysMenuEntity entity : menuList) {
            //目录
            if (entity.getType() == SysConstant.MenuType.CATALOG.getValue()) {
                entity.setList(getMenuTreeList(queryListParentId(entity.getMenuId(), menuIdList), menuIdList));
            }
            subMenuList.add(entity);
        }

        return subMenuList;
    }

}
